import { Component, Input, ViewChild, ElementRef, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Subscription } from 'rxjs/Subscription';
import { Observable } from 'rxjs/Observable';
import { IndicatorModel, CheckBoxModel, DataRowModel } from './models/indicator.model';
import { ChartColumnModel } from './models/chartColumn.model';
import * as _ from 'lodash';
import { ClusterComponent } from '../../../riskCluster/cluster.component';
import { environment } from '../../../../../../environments/environment';
import { UtilsService } from '../../../../../shared/services/utils.service';
import { NgxSmartModalService } from 'ngx-smart-modal';
import { ClusterService } from '../../../riskCluster/cluster.service';

/**
 * MEI indicator details component
 *
 * Author: Sorin Spiru
 * Date: 16.01.2018
 */
@Component({
    selector: 'company-indicator',
    templateUrl: './companyIndicator.component.html',
    styleUrls: ['./companyIndicator.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class CompanyIndicatorComponent extends ClusterComponent {
    private sub: Subscription;
    public readonly resourcesUrl: string = environment.resourcesUrl;
    public tickboxGroups: CheckBoxModel[];
    public dataTable: DataRowModel[];
    public dataTableYears: number[];
    public dataTableNames: string[];
    public indicatorDetails: IndicatorModel;
    public getUrlFriendlyName: Function = UtilsService.getUrlFriendlyName;

    @Input() parentId: string = "";
    @Input() indicatorIndex: number;
    @Input() canExpand: boolean;
    @Input() indicator: any;
    @Input() showAxis: boolean;
    @Input() columns: ChartColumnModel[];
    @Input() subTitle: string;

    @Input() getIndicatorFunc: Function;
    @Input() getIndicatorParams: any[];

    @ViewChild('indicatorPanelLink') panelLink: ElementRef;

    constructor(
        public ngxSmartModalService: NgxSmartModalService,
        private cdRef: ChangeDetectorRef) {
        super(cdRef);
    }

    ngOnInit() {
    }

    get displayCode() {
        return this.indicator.code.substring(0, 2) !== 'CG';
    }

    getCleanIndicatorCode(code) {
        return code ? code.split('.').join('_') : '';
    }

    public clickToToggle(): void {
        if (this.canExpand == true)
            this.panelLink.nativeElement.click();
    }

    public collapseToggle(code: string): void {
        if (this.indicatorDetails == undefined && this.getIndicatorFunc) {
            //get indicator details
            this.getIndicatorFunc.apply(this, this.getIndicatorParams).subscribe(data => {
                this.indicatorDetails = data;

                // split checkboxes
                let numCheckboxes = this.indicatorDetails.checkBoxes.length;
                this.tickboxGroups = _.chunk(this.indicatorDetails.checkBoxes, (numCheckboxes > 4 ? Math.ceil(numCheckboxes / 2) : numCheckboxes));

                this.dataTable = this.indicatorDetails.dataTable;
                this.dataTableNames = _(this.dataTable).groupBy('name').map((items, key) => key).orderBy().value();
                this.dataTableYears = _(this.dataTable).groupBy('year').map((items, key) => key).orderBy().value();
                this.cdRef.markForCheck();
            });
        }
        this.ngxSmartModalService.getModal('indicator' + this.getCleanIndicatorCode(code)).open();
    }

    public getTableValue(name: string, year: number): string {
        let cell = this.dataTable.find(x => x.name == name && x.year == year);
        return cell != undefined ? cell.value : 'N/A';
    }

    public formatValue(indicator: any, column: ChartColumnModel): string {
        let value: number = column.hasNoValue == true ? indicator[column.valueField] : indicator[column.valueField].value;
        if (value == undefined) value = 0;
        if (column.formatMethod) value = column.formatMethod(value);
        return value.toFixed(column.decimals).toString() + ' ' + column.ratingUnit;
    }
}